package com.heima.wemedia.gateway.filter;


import com.cjq.jwt.JwtUtil;
import com.heima.wemedia.gateway.constant.RedisConstant;



import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 检查请求路径是否包含登录接口，如果是则直接放行
        boolean contains = request.getURI().getPath().contains("/login");
        if (contains){
            log.error("登录放行");
            return chain.filter(exchange);
        }

        // 从请求头中获取token
        String token = getTokenFromHeader(request);
        if (isInValidStr(token)){
            log.error("拦截:{}","无Token");
            return unauthorized(response);
        }

        // 解析JWT token获取声明信息
        Claims claims;
        try {
            claims = jwtUtil.parseToken(token, SignatureAlgorithm.HS256);
        } catch (Exception e) {
            log.error("拦截:{}","Token验证失败");
            return unauthorized(response);
        }

        // 验证声明信息有效性
        if (claims == null) {
            log.error("拦截:{}","无载荷");
            return unauthorized(response);
        }
        // 从Redis中验证token是否存在
        String jwtId = claims.getId();
        String rUserId;
        try {
            rUserId = redisTemplate.opsForValue().get(RedisConstant.APP_JWT_TOKEN_KEY + jwtId);
        } catch (Exception e) {
            log.error("拦截:{}","Redis无记录");
            return unauthorized(response);
        }

        // 验证Redis中获取的用户ID是否有效
        if (isInValidStr(rUserId)){
            log.error("拦截:{}","Redis无用户ID记录");
            return unauthorized(response);
        }

        // 将用户ID添加到请求头中并继续执行过滤器链
        ServerHttpRequest id = request.mutate().header("id", rUserId).build();
        exchange.mutate().request(id).build();
        return chain.filter(exchange);
    }
    private String getTokenFromHeader(ServerHttpRequest request) {
        return request.getHeaders().getFirst("token");
    }

    private boolean isInValidStr(String token) {
        return StringUtils.isEmpty(token);
    }

    private Mono<Void> unauthorized(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
    /**
     * 优先级设置  值越小  优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
